<!--
 * @Description: 新建/编辑结算设置
 * @Author: py
 * @Date: 2024-12-30
-->
<script setup lang="ts">
import type { FormInstance } from 'element-plus'
import type { VxeGridProps } from 'vxe-table'
import { formatTime } from '@fl/utils'

import { createSettingApi, settingDetailsApi, updateSettingApi } from '@fl/api/charge-settle'
import type { SettingParams } from '@fl/api/charge-settle/model/setting-model'
import { SubmitBtn } from '@fl/components'

import { useDicts } from '../hooks/use-dicts'

const props = withDefaults(defineProps<{
    data?: any
    operatorOptions?: any[]
    operatorMap?: any
    vendorOptions?: any[]
    vendorMap?: any
}>(), {
    data: () => {},
    operatorOptions: () => [],
    operatorMap: () => {},
    vendorOptions: () => [],
    vendorMap: () => {},
})

const emits = defineEmits(['success'])

const { getDictOptions } = useDicts()

const busiTypeOptions = getDictOptions('oBusinessType')
const rateTypeOptions = getDictOptions('oRateType')

// data: rowData,
const { operatorOptions, operatorMap, vendorOptions, vendorMap } = toRefs(props)
const visible = defineModel<boolean>('visible', { required: true })
const id = defineModel<number | string>('id', { required: true })
const isEditMode = computed(() => {
    return !!id.value
})

const title = computed(() => {
    return isEditMode.value ? '编辑结算设置' : '新建结算设置'
})

const formRef = ref()
const oDay = day()
const todayLabel = oDay.format('YYYY-MM-DD')
const initialState = {
    settlementType: '1',
    effectiveDate: todayLabel,
    vendorId: '',
    settlementRatio: 0,
    operatorId: '1',
    ratioType: '1',
}
const formValues = ref({ ...initialState })
const rules = {
    settlementType: [{ message: '请选择结算业务类型', required: true, trigger: 'change' }],
    effectiveDate: [{ message: '请选择生效日期', required: true, trigger: 'change' }],
    vendorId: [{ message: '请选择合作商', required: true, trigger: 'change' }],
    settlementRatio: [{ message: '请输入结算比例', required: true, trigger: 'blur' }],
    operatorId: [{ message: '请选择运营商', required: true, trigger: 'change' }],
    ratioType: [{ message: '请选择结算比例类型', required: true, trigger: 'change' }],
}
// 阶梯结算比例表单配置
const rateGridOptions = reactive<VxeGridProps>({
    border: 'inner',
    stripe: false,
    columns: [
        { title: '序号', type: 'seq', width: 60 },
        { slots: { default: 'electRange' }, title: '电量区间', width: 370 },
        { slots: { default: 'settleRate' }, title: '结算比例(%)' },
        { slots: { default: 'operate' }, title: '操作', width: 160 },
    ],
    // headerCellClassName: 'table-header-cell',
    // headerRowClassName: 'bg-white',
    maxHeight: 360,
    minHeight: 60,
    size: 'mini',
})

type RateItem = {
    electricEnd: null | number
    electricStart: null | number
    id: string
    rateValidateMessage: string
    rateValidateState: string
    settleRatio: null | number
    validateMessage: string
    validateState: string
}
// 阶梯结算比例表单数据
const rateList = ref<RateItem[]>([])

const isFormLoading = ref(false)
// 获取表单详情信息-回显
function getFormDetails() {
    isFormLoading.value = true
    settingDetailsApi(id.value).then((data) => {
        const {
            settlementType,
            effectiveDate,
            vendorId,
            settlementRatio,
            operatorId,
            ratioType,
            settlementRatioList,
        } = data
        formValues.value = {
            settlementType: String(settlementType),
            effectiveDate: formatTime(effectiveDate, 'yyyy-MM-dd'),
            vendorId,
            settlementRatio,
            operatorId,
            ratioType: String(ratioType),
        }

        rateList.value = settlementRatioList?.map((item) => {
            return {
                electricEnd: item.chargeMax,
                electricStart: item.chargeMin,
                id: item.id,
                rateValidateMessage: '',
                rateValidateState: 'success',
                settleRatio: item.settlementRatio,
                settlementSettingId: item.settlementSettingId,
                validateMessage: '',
                validateState: 'success',
            }
        })
    }).finally(() => {
        isFormLoading.value = false
    })
}

watchEffect(() => {
    if (id.value) {
        getFormDetails()
    }
})

/**
watchEffect(() => {
    if (isEditMode.value && rowData.value) {
        formValues.value = {
            ...rowData.value,
            settlementType: String(rowData.value.settlementType),
            ratioType: String(rowData.value.ratioType),
        }
        // rateList.value = [
        //     {
        //         electricEnd: 10,
        //         electricStart: 1,
        //         id: '3026',
        //         rateValidateMessage: '',
        //         rateValidateState: 'success',
        //         settleRatio: 5,
        //         validateMessage: '',
        //         validateState: 'success',
        //     },
        // ]
    }
})
*/

// 结算比例类型切换
function handleRateTypeChange() {
    if (formValues.value.ratioType === '2') { // 阶梯式
        // addRangeItem()
        formValues.value.settlementRatio = 0
    }
    else {
        rateList.value = []
    }
}

// 新增一条空数据
function addRangeItem() {
    rateList.value.push({
        electricEnd: null,
        electricStart: null,
        id: `${new Date().getTime()}`,
        rateValidateMessage: '',
        rateValidateState: '',
        settleRatio: null,
        validateMessage: '',
        validateState: '',
    })
}
// 前端伪删除
function deleteRangeItem(oItem) {
    const targetIndex = rateList.value.findIndex((v: any) => v.id === oItem.id)
    rateList.value.splice(targetIndex, 1)
}

// 验证阶梯比例Table 单行表单
function validateRow(row: any, index: number) {
    let isValid = true
    let message = ''

    if (row.electricStart === null) {
        isValid = false
        message = '起始电量不能为空'
    }
    else if (row.electricEnd === null) {
        isValid = false
        message = '结束电量不能为空'
    }
    else if (row.electricStart >= row.electricEnd) {
        isValid = false
        message = '起始电量不能大于或等于结束电量'
    }

    // if (index > 0) {
    //     const previousRow = rateList.value[index - 1]
    //     if (row.electricStart < previousRow.electricEnd) {
    //         isValid = false
    //         message = '当前行的起始电量不能小于前一行的结束电量'
    //     }
    //     if (row.electricEnd <= previousRow.electricEnd) {
    //         isValid = false
    //         message = '当前行的结束电量必须大于前一行的结束电量'
    //     }
    // }

    if (!isValid) {
        rateList.value[index].validateState = 'error'
        rateList.value[index].validateMessage = message
    }
    else {
        rateList.value[index].validateState = 'success'
        rateList.value[index].validateMessage = ''
    }

    if (row.settleRatio === null) {
        isValid = false
        rateList.value[index].rateValidateState = 'error'
        rateList.value[index].rateValidateMessage = '结算比例不能为空'
    }
    else {
        rateList.value[index].rateValidateState = 'success'
        rateList.value[index].rateValidateMessage = ''
    }

    return isValid
}

const isPending = ref(false)
// 提交
async function handleSubmit(formEl: FormInstance | undefined) {
    if (!formEl)
        return
    await formEl.validate(async (valid) => {
        if (valid) {
            const {
                settlementType,
                effectiveDate,
                vendorId,
                ratioType,
                settlementRatio,
                operatorId,
            } = formValues.value
            let oParams: SettingParams = {
                settlementType,
                effectiveDate,
                vendorId,
                vendorName: vendorMap.value[vendorId],
                ratioType,
                operatorId,
                operatorName: operatorMap.value[operatorId],
            }

            if (ratioType === '2') { // 阶梯式
                if (rateList.value.length === 0) {
                    ElMessage({
                        message: '结算比例设置不能为空',
                        type: 'warning',
                    })
                    return
                }

                let allRowsValid = true
                rateList.value.forEach((row, index) => {
                    if (!validateRow(row, index)) {
                        allRowsValid = false
                    }
                })
                if (!allRowsValid) {
                    return
                }

                const settlementRatioList = rateList.value.map((item) => {
                    const oSetting = {
                        chargeMin: item.electricStart,
                        chargeMax: item.electricEnd,
                        settlementRatio: item.settleRatio,
                    }

                    if (isEditMode.value) {
                        return {
                            ...oSetting,
                            settlementSettingId: id.value,
                        }
                    }
                    else {
                        return oSetting
                    }
                })
                oParams = {
                    ...oParams,
                    settlementRatioList,
                }
            }
            else {
                oParams = {
                    ...oParams,
                    settlementRatio,
                }
            }

            // isFormLoading.value = true;
            // console.log(oParams)

            try {
                if (isEditMode.value) {
                    oParams = {
                        ...oParams,
                        id: id.value,
                    }
                    await updateSettingApi(oParams)
                    ElMessage.success('编辑成功')
                }
                else {
                    await createSettingApi(oParams)
                    ElMessage.success('新增成功')
                }

                visible.value = false
                emits('success')
            }
            catch (error) {
                console.error(error)
            }
            // finally {
            //     isFormLoading.value = false
            // }
        }
    })
}

// 取消
function handleCancel() {
    visible.value = false
}

// 重置
function handleReset(formEl: FormInstance | undefined) {
    id.value = ''
    formValues.value = { ...initialState }
    rateList.value = []
    if (!formEl)
        return
    // formRef.value.formInstance.resetFields()
    formEl.resetFields()
}
</script>

<template>
    <PlusDialog v-model="visible"
                :title="title"
                width="1000"
                class="settings-dialog"
                close-on-press-escape
                @cancel="handleCancel"
                @closed="handleReset(formRef)"
    >
        <ElSkeleton v-if="isFormLoading"
                    animated
        />

        <el-form v-else
                 ref="formRef"
                 :model="formValues"
                 :rules="rules"
                 label-position="top"
                 label-width="auto"
        >
            <el-row :gutter="24">
                <el-col :span="12">
                    <el-form-item label="运营商名称"
                                  prop="operatorId"
                    >
                        <el-select v-model="formValues.operatorId"
                                   placeholder="请选择运营商"
                                   :disabled="isEditMode"
                        >
                            <el-option v-for="item in operatorOptions"
                                       :key="item.dictValue"
                                       :label="item.dictLabel"
                                       :value="item.dictValue"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>

                <el-col :span="12">
                    <el-form-item label="结算业务类型"
                                  prop="settlementType"
                    >
                        <el-select v-model="formValues.settlementType"
                                   placeholder="请选择结算业务类型"
                                   :disabled="isEditMode"
                        >
                            <el-option v-for="item in busiTypeOptions"
                                       :key="item.value"
                                       :label="item.label"
                                       :value="item.value"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row :gutter="24">
                <el-col :span="12">
                    <el-form-item label="合作商名称"
                                  prop="vendorId"
                    >
                        <el-select v-model="formValues.vendorId"
                                   placeholder="请选择合作商"
                                   :disabled="isEditMode"
                        >
                            <el-option v-for="item in vendorOptions"
                                       :key="item.dictValue"
                                       :label="item.dictLabel"
                                       :value="item.dictValue"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>

                <el-col :span="12">
                    <el-form-item label="生效日期"
                                  prop="effectiveDate"
                    >
                        <el-date-picker v-model="formValues.effectiveDate"
                                        type="date"
                                        placeholder="请选择生效日期"
                                        value-format="YYYY-MM-DD"
                                        style="width: 100%"
                        />
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row :gutter="24">
                <el-col :span="12">
                    <el-form-item label="结算比例类型"
                                  prop="ratioType"
                    >
                        <el-select v-model="formValues.ratioType"
                                   placeholder="请选择结算比例类型"
                                   @change="handleRateTypeChange"
                        >
                            <el-option v-for="item in rateTypeOptions"
                                       :key="item.value"
                                       :label="item.label"
                                       :value="item.value"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>

                <el-col v-if="formValues.ratioType === '1'"
                        :span="12"
                >
                    <el-form-item label="结算比例"
                                  prop="settlementRatio"
                    >
                        <el-input-number v-model="formValues.settlementRatio"
                                         class="rate-input"
                                         :controls="false"
                                         :min="0"
                                         :max="100"
                                         :precision="2"
                                         placeholder="请输入结算比例"
                        />

                        <span class="rate-unit">%</span>
                    </el-form-item>
                </el-col>

                <el-col v-else
                        :span="24"
                >
                    <vxe-grid class="w-full"
                              v-bind="rateGridOptions"
                              :data="rateList"
                    >
                        <template #electRange="{ row }">
                            <!-- @change="validateRow(row, rowIndex)" -->
                            <el-input-number v-model="row.electricStart"
                                             class="rate-input-r"
                                             :controls="false"
                                             :min="0"
                                             :precision="0"
                            />

                            <span class="px-8">-</span>

                            <el-input-number v-model="row.electricEnd"
                                             class="rate-input-r"
                                             :controls="false"
                                             :min="0"
                                             :precision="0"
                            />

                            <div v-if="row.validateState === 'error'"
                                 class="error-message"
                            >
                                {{ row.validateMessage }}
                            </div>
                        </template>

                        <template #settleRate="{ row }">
                            <el-input-number v-model="row.settleRatio"
                                             class="rate-input-r"
                                             :controls="false"
                                             :min="0"
                                             :max="100"
                                             :precision="2"
                            />

                            <div v-if="row.rateValidateState === 'error'"
                                 class="error-message"
                            >
                                {{ row.rateValidateMessage }}
                            </div>
                        </template>

                        <template #operate="{ row }">
                            <div class="row-btns">
                                <span class="btn-operate"
                                      @click="deleteRangeItem(row)"
                                >
                                    删除
                                </span>
                            </div>

                            <!-- <el-popconfirm title="要删除吗？"
                                           @confirm="deleteRangeItem(row)"
                            >
                                <template #reference>
                                    <div class="row-btns">
                                        <span class="btn-operate">
                                            删除
                                        </span>
                                    </div>
                                </template>
                            </el-popconfirm> -->
                        </template>

                        <template #bottom>
                            <div class="table-footer">
                                <el-button type="primary"
                                           size="small"
                                           plain
                                           @click="addRangeItem"
                                >
                                    添加
                                </el-button>
                            </div>
                        </template>
                    </vxe-grid>
                </el-col>
            </el-row>
        </el-form>

        <template #footer>
            <div class="pr-32 ml-auto">
                <el-button @click="handleCancel">
                    取消
                </el-button>

                <SubmitBtn type="primary"
                           :loading="isPending"
                           @click="handleSubmit(formRef)"
                >
                    保存
                </SubmitBtn>
            </div>
        </template>
    </PlusDialog>
</template>

<style lang="less">
.settings-dialog {
    border-radius: 4px;
    overflow: hidden;
    padding: 56px 0 16px !important;

    .el-dialog__header {
        height: 56px !important;
        padding: 0 32px !important;
        line-height: 56px;

        .el-dialog__title {
            color: #1d2129;
        }

        .el-dialog__headerbtn {
            top: 50%;
            transform: translateY(-50%);
            right: 16px;
        }
    }

    .el-dialog__body {
        padding: 24px 32px 8px !important;
    }

    .el-form-item--default {
        margin-bottom: 16px;
    }

    .el-form-item__label {
        color: #1d2129;
    }

    .el-select__placeholder {
        color: #1d2129;

        &.is-placeholder {
            color: #c9cdd4;
        }
    }

    .el-input__inner {
        color: #1d2129;

        &::placeholder {
            color: #c9cdd4;
        }
    }
}
</style>

<style lang="less" scoped>
@import '../../custom.less';

// 固定结算比例输入框
.rate-input {
    width: 100%;

    :deep(.el-input__wrapper) {
        padding-right: 30px;
    }

    :deep(.el-input__inner) {
        text-align: left;
    }
}

// 固定结算比例单位
.rate-unit {
    position: absolute;
    right: 15px;
}

// 阶梯结算比例输入框
.rate-input-r {
    width: 100px;

    :deep(.el-input__wrapper) {
        padding-left: 10px;
        padding-right: 10px;
    }
}

// 阶梯结算比例校验失败提示
.error-message {
    padding-top: 2px;
    font-size: 12px;
    line-height: 1;
    color: var(--el-color-danger);
}

.table-footer {
    padding: 10px 0;
    text-align: center;
    border-bottom: 1px solid #ebeef5;
}
</style>
